package org.shagin.jfin.ui.date.cond;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JPanel;

import org.shagin.jfin.core.Debug;
import org.shagin.jfin.date.DateUtils;
import org.shagin.jfin.date.cond.IDateCondition;
import org.shagin.jfin.date.cond.Weekly;
import org.shagin.jfin.ui.UI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The Class WeeklyPane.
 */
@SuppressWarnings("serial")
public class JWeeklyPane extends DateConditionPane<Weekly> {

    private static final Logger log = LoggerFactory
            .getLogger(JWeeklyPane.class);

    private Map<Integer, JCheckBox> items = new HashMap<Integer, JCheckBox>();
    private ActionListener itemActionListener;

    /**
     * Instantiates a new weekly pane.
     */
    public JWeeklyPane() {
        super();
        dateCondition = new Weekly(new int[]{});
        addListeners();
        initView();
    }

    /**
     * Adds the listeners.
     */
    private void addListeners() {
        itemActionListener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                Debug.traceEnter(log);
                fireChangedEvent();
            }
        };
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void fireChangedEvent() {
        getValue().setWeekDays(getWeekDays());
        super.fireChangedEvent();
    }
    /**
     * Creates the tool panel.
     * 
     * @return the j panel
     */
    private JPanel createToolPanel() {
        JPanel toolPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, UI.HGAP,
                UI.VGAP));
        // TODO Localize
        JButton btnSelectAll = new JButton("Выбрать все");
        btnSelectAll.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                selectAll(true, true);
            }
        });

        // TODO Localize
        JButton btnUnSelectAll = new JButton("Ничего");
        btnUnSelectAll.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                selectAll(false, true);
            }
        });
        toolPanel.add(btnSelectAll);
        toolPanel.add(btnUnSelectAll);
        return toolPanel;
    }

    /**
     * Inits the view.
     */
    private void initView() {
        setLayout(new BorderLayout());
        JPanel panel = new JPanel(new GridLayout(1, 7));
        for (int i = Calendar.SUNDAY; i <= Calendar.SATURDAY; i++) {
            panel.add(newItem(i));
        }
        add(panel, BorderLayout.CENTER);
        add(createToolPanel(), BorderLayout.SOUTH);
    }

    /**
     * New item.
     * 
     * @param i the i
     * @return the j check box
     */
    private JCheckBox newItem(Integer i) {
        JCheckBox item = new JCheckBox(DateUtils.getWeekDay(i));
        item.addActionListener(itemActionListener);
        items.put(i, item);
        return item;
    }

    /**
     * Gets the selected.
     * 
     * @return the selected
     */
    private List<Integer> getSelected() {
        List<Integer> result = new ArrayList<Integer>();
        for (Map.Entry<Integer, JCheckBox> entry : items.entrySet()) {
            if (entry.getValue().isSelected())
                result.add(entry.getKey());
        }
        return result;
    }

    /**
     * Select all.
     * 
     * @param selected the selected
     */
    private void selectAll(boolean selected, boolean fireEvent) {
        Debug.traceEnter(log);
        for (Map.Entry<Integer, JCheckBox> entry : items.entrySet()) {
            entry.getValue().setSelected(selected);
        }
        if (fireEvent)
            fireChangedEvent();
    }

    private int[] getWeekDays() {
        List<Integer> sel = getSelected();
        int[] result = new int[sel.size()];
        for (int i = 0; i < result.length; i++) {
            result[i] = sel.get(i).intValue();
        }
        return result;
    }

    private void setWeekDays(int[] weekDays) {
        Debug.traceEnter(log);
        selectAll(false, false);
        for (int i = 0; i < weekDays.length; i++) {
            JCheckBox cb = items.get(weekDays[i]);
            cb.setSelected(true);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Weekly getValue() {
        return (Weekly) dateCondition;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getTitle() {
        // TODO Localize
        return "Каждую неделю";
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setDateCondition(IDateCondition dateCondition) {
        Debug.traceEnter(log);
        super.setDateCondition(dateCondition);
        setWeekDays(getValue().getWeekDays());
    }

}
